package net.zzy.pbbot.plugin.dxx.scheduled;

import com.alibaba.fastjson.JSON;
import lombok.SneakyThrows;
import net.lz1998.pbbot.bot.Bot;
import net.lz1998.pbbot.bot.BotContainer;
import net.lz1998.pbbot.utils.Msg;
import net.zzy.pbbot.plugin.dxx.entity.CommitBody;
import net.zzy.pbbot.plugin.dxx.entity.DxxDaoEntity;
import net.zzy.pbbot.plugin.dxx.entity.DxxResp;
import net.zzy.pbbot.plugin.dxx.mapper.DxxMapper;
import net.zzy.pbbot.util.HttpsUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static net.zzy.pbbot.finalfield.Api.DXX_COMMIT;
import static net.zzy.pbbot.finalfield.FinalInt.BOT_QQ;
import static net.zzy.pbbot.finalfield.FinalStr.PHONE_USER_AGENT;

/**
 * @author zhuZhaoYang
 * @date 2021/9/28 21:58
 */
@Component
public class EveryWeekDxx {

    private DxxMapper dxxMapper;

    @Autowired
    public void setDxxMapper(DxxMapper dxxMapper) {
        this.dxxMapper = dxxMapper;
    }

    private BotContainer botContainer;

    @Autowired
    public void setBotContainer(BotContainer botContainer) {
        this.botContainer = botContainer;
    }

    /**
     * 每周三上午10时
     */
    @SneakyThrows
    @Scheduled(cron = "0 0 10 ? 3 ?")
    public void everyWeekDxx() {
        Bot bot = botContainer.getBots().get(BOT_QQ);
        if (bot == null) {
            return;
        }
        List<DxxDaoEntity> dxxDaoEntities = dxxMapper.selectList(null);
        for (DxxDaoEntity dxxDaoEntity : dxxDaoEntities) {
            Map<String, String> headers = new HashMap<>();
            headers.put("token", dxxDaoEntity.getToken());
            headers.put("User-Agent", PHONE_USER_AGENT);
            CommitBody commitBody = new CommitBody();
            commitBody.setName(dxxDaoEntity.getName());
            commitBody.setTel(dxxDaoEntity.getTel());
            commitBody.setOrg("#2#5942#6068#6885#");
            commitBody.setLastOrg("6885");
            commitBody.setOrgName("计算机科学与技术专业2019级5班团支部");
            commitBody.setAllOrgName("#高校#成都信息工程大学#计算机学院团委#计算机科学与技术专业2019级5班团支部#");
            String post = HttpsUtils.post(DXX_COMMIT, JSON.toJSONString(commitBody), headers);
            DxxResp dxxResp = JSON.parseObject(post, DxxResp.class);
            Msg.builder().text("已自动提交青年大学习,执行结果：").text(dxxResp.getMsg()).sendToFriend(bot, Long.parseLong(dxxDaoEntity.getQq()));
        }

    }
}
